from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt

# 注意了 要使用.来引入包 否则会一直报错
from .utils.redis_utils import redis_util

from product.models import Product
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import User, UserRegistrationForm, UserLoginForm

'''
    main首页 
    首先处理是否登录 
    从redis中获取token
'''
@csrf_exempt
def main(request):
    username = request.session.get('token')
    is_login,is_admin = False,False
    if username is None:
        is_login = False
    else:
        username = redis_util.gettoekn(username)
        if username is None:
            is_login = False
        else:
            is_login = True
            if username == 'admin':
                is_admin = True
    data_list = Product.objects.all()
    # 处理自定义值
    try:
        # 获取用户选择的每页显示数量，默认为 10
        per_page = int(request.GET.get('per_page', 10))
        per_page = int(per_page)  # 将 per_page 转换为整数
        if per_page <= 0:  # 如果输入的值小于等于0，设置为默认值10
            per_page = 10
    except (ValueError, TypeError):  # 如果 per_page 不是数字，设置为默认值10
        per_page = 10

    # 分页
    paginator = Paginator(data_list, per_page)
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.get_page(page_number)  # 获取当前页
    except PageNotAnInteger:  # 如果 page 不是整数，跳转到第一页
        page_obj = paginator.get_page(1)
    except EmptyPage:  # 如果 page 超出范围，跳转到最后一页
        page_obj = paginator.get_page(paginator.num_pages)

    # 允许的每页显示数量列表
    allowed_per_page = [10, 20, 50, 100, 200]

    return render(request, 'main.html', {
        'data_list': page_obj,
        'per_page': per_page,  # 将每页显示数量传递给模板
        'allowed_per_page': allowed_per_page,
        'is_admin': is_admin,
        'is_login': is_login,
    })

def getUserNotAdmin():
    return User.objects.exclude(username='admin')

@csrf_exempt
def register(request):
    if request.method == 'POST':
        # 从 request.POST 中提取数据
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # 注册后自动登录
            request.session['token'] = redis_util.generate_toekn(user.username,user.username)
            # 处理有效的表单数据
            return redirect('main')  # 注册成功后跳转到成功页面
    else:
        # 如果是 GET 请求，创建一个空表单
        form = UserRegistrationForm()
    return render(request, 'register.html', {'form': form})  # 渲染注册页面

@csrf_exempt
def login(request):
    try:
        if request.method == 'POST':
            # 从 request.POST 中提取数据
            form = UserLoginForm(request.POST)
            if form.is_valid():
                username = form.cleaned_data['username']
                token = redis_util.generate_toekn(username, username)
                request.session['token'] = token
                return redirect('main')  # 重定向到首页
        else:
            form = UserLoginForm()
        return render(request, 'login.html', {'form': form})  # 渲染注册页面
    except Exception as e:
        raise e

@csrf_exempt
def logout(request):
    # 清空token  并清空redis
    username = request.session.get('token')
    request.session['token'] = None
    redis_util.delete_toekn(username)
    # 重定向到首页
    return redirect('main')  # 渲染注册页面
